package com.gel.springai.redis.starter;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;

import java.io.Serializable;
import java.util.Map;
import java.util.Objects;

/*序列化的Message包装类*/
public class SerializableMessage implements Serializable {

    private static final long serialVersionUID = 1L;

    //定义Message类型枚举
    public enum MessageType {
        USER,
        SYSTEM,
        ASSISTANT
    }

    private final MessageType messageType;
    private final String textContent;
    private final Map<String, Object> metadata;

    // 显式添加getter方法（替代Lombok）
    public MessageType getMessageType() {
        return messageType;
    }

    public String getTextContent() {
        return textContent;
    }

    public Map<String, Object> getMetadata() {
        return metadata;
    }

    public SerializableMessage(Message message) {
        this.messageType = getMessageType(message);
        this.textContent = message.getText();
        this.metadata = message.getMetadata();
    }

    //判断类型
    private MessageType getMessageType(Message message) {
        if (message instanceof SystemMessage) return MessageType.SYSTEM;
        if (message instanceof UserMessage) return MessageType.USER;
        if (message instanceof AssistantMessage) return MessageType.ASSISTANT;
        throw new IllegalArgumentException("Unknown message type" + message.getClass().getName());

    }

    //类型转换（SerializableMessage-》Message）
    public Message toMessage() {
        switch (messageType) {
            case USER:
                return new UserMessage(textContent);
            case SYSTEM:
                return new SystemMessage(textContent);
            case ASSISTANT:
                return new AssistantMessage(textContent, metadata);
            default:
                throw new IllegalArgumentException("Unknown message type" + messageType);
        }
    }

    @JsonCreator
    public SerializableMessage(
            @JsonProperty("messageType") MessageType messageType,
            @JsonProperty("textContent") String textContent,
            @JsonProperty("metadata") Map<String, Object> metadata
    ) {
        this.messageType = messageType;
        this.textContent = textContent;
        this.metadata = metadata;
    }
}